package com.medium.house.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件处理工具类
 */
public class FileUtil
{
	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	public static String readFileToString(String file) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(file));
		StringBuilder stringBuilder = new StringBuilder();
		String ls = System.getProperty("line.separator");

		String line;
		while ((line = reader.readLine()) != null) {
			stringBuilder.append(line);
			stringBuilder.append(ls);
		}
		reader.close();
		return stringBuilder.toString();
	}

	/**
	 * 上传图片
	 * @param is 文件流
	 * @param filePath 目的文件路径, 包含文件全名
	 */
	public static boolean uploadFile(InputStream is, String filePath) {
		if (is == null || filePath == null || filePath.equals("")) {
			return false;
		}

		try {
			String folderPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
			File folder = new File(folderPath);
			if (!folder.exists()) {
				folder.mkdirs();
			}

			File file = new File(filePath);
			FileUtils.copyInputStreamToFile(is, file);
			return true;
		} catch (Exception e) {
			logger.error("File upload failed when creating " + filePath);
			logger.debug(e.getMessage(), e);
		}
		return false;
	}

	/**
	 * 删除指定文件, 如果是目录则跳过
	 *
	 * @param path
	 * @return
	 */
	public static boolean deleteFile(String path) {
		try {
			File file = new File(path);
			if (file.isFile())
				return file.delete();
			else
				return false;
		} catch(SecurityException e) {
			return false;
		}
	}

	/**
	 * 获取目标文件夹(包含子目录)下的所有以某扩展名结尾的文件的路径
	 * 如果扩展名未指定, 则返回所有文件
	 *
	 * @param path
	 * @param extension
	 * @return
	 */
	public static List<String> getAllFiles(String path, String extension) {

		File folder = new File(path);
		File[] files = folder.listFiles();
		List<String> paths = new ArrayList<String>();

		if(files == null)
			return paths;

		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile()) {
				if (extension != null && extension.length() > 0) {
					// 扩展名过滤
					String fileName = files[i].getName();
					if (extension.equalsIgnoreCase(getExtension(fileName))) {
						paths.add(files[i].getAbsolutePath());
					}
				} else {
					paths.add(files[i].getAbsolutePath());
				}
			} else if (files[i].isDirectory()) {
				List<String> subFiles = getAllFiles(files[i].getAbsolutePath(), extension);
				if (subFiles != null && subFiles.size() > 0) {
					paths.addAll(subFiles);
				}
			}
		}
		return paths;
	}

	/**
	 * 获取文件扩展名
	 */
	public static String getExtension(String filename) {
		if (filename == null || filename.length() == 0) return "";
		int i = filename.lastIndexOf('.');
		if (i > -1 && i < (filename.length() - 1)) {
			return filename.substring(i + 1);
		} else {
			return "";
		}
	}

	/**
	 * 获取文件最后修改时间
	 */
	public static Date getLastModified(String fullFilePath) {
		File file = new File(fullFilePath);
		if (file.exists())
			return new Date(file.lastModified());
		else
			return null;
	}

	/**
	 * 移动文件至新目录
	 * @param srcFilePath 原文件地址(包含文件名)
	 * @param destPath 新文件路径(不包含文件名)
	 * @param destFileName 新文件名(不包含路径), 为空则使用原文件名
	 */
	public static void moveFile(String srcFilePath, String destPath, String destFileName) {
		File srcFile = new File(srcFilePath);
		moveFile(srcFile, destPath, destFileName);
	}

	public static void moveFile(File file, String destPath, String destFileName) {
		File destFolder = new File(destPath);
		if (!destFolder.isDirectory()) {
			destFolder.mkdirs();
		}

		if (destFileName == null || destFileName.length() == 0) {destFileName = file.getName();}
		File destFile = new File(destPath + destFileName);
		file.renameTo(destFile);
	}

	/**
	 * 七牛云文件上传
	 * @param is
	 */
	public static String qnyFileUpInputStream(InputStream is, String accessKey, String secretKey, String bucket) {
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		//...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		//...生成上传凭证，然后准备上传
		/*String accessKey = "qm_95wtC7TOToopYScqOaGoI4jMrh1oR7Gwmf0WD";
		String secretKey = "GWtQo8CsCOy_vnB4JHGwtl0LpOHCTCVTPGg0h8T7";
		String bucket = "test-bucket";*/
		//默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(is,key,upToken,null, null);
			//解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			logger.info("FileUtil.qnyFileUpInputStream() try result:{},key:{},hash:{}",putRet,putRet.key,putRet.hash);
			return putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			logger.info("FileUtil.qnyFileUpInputStream() catch ex:{}",r);
			try {
				System.err.println();
				logger.info("FileUtil.qnyFileUpInputStream() r.bodyString:{}",r.bodyString());
			} catch (QiniuException ex2) {
				logger.info("FileUtil.qnyFileUpInputStream() r.bodyString ex:{}",ex2.getMessage());
			}
		}finally {
			try {
				is.close();
			} catch (IOException e) {
				logger.error("FileUtil.qnyFileUpInputStream() finally IO close Exception result:{}",e.getMessage());
				e.printStackTrace();
			}
		}
		return null;
	}
}
